using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using Acms.Bll;

namespace Acms.AcmsControls
{
    public class TemplatePage : Page
    {
        /*protected override void OnPreInit(EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["AcmsPostId"]))
            {
                try
                {
                    postId = int.Parse(Request.QueryString["AcmsPostId"]);
                }
                catch
                { }
            }

            if (!string.IsNullOrEmpty(Request.QueryString["AcmsSiteId"]))
            {
                try
                {
                    siteId = int.Parse(Request.QueryString["AcmsSiteId"]);
                }
                catch
                { }
            }

            SiteVersion = DateTime.Now;
            if (Request.QueryString["AcmsSV"] == "Pending")
            {
                SiteVersion = null;
            }
            else if(Request.QueryString["AcmsSV"] != null)
            {
                try
                {
                    SiteVersion = DateTime.Parse(Request.QueryString["AcmsSV"]);
                }
                catch
                {
                }
            }

            base.OnPreInit(e);
        }*/

        //protected virtual string PageTitleFormat()
        //{
        //    return "{0} - {1}{2}";
        //}

        protected override void OnPreLoad(EventArgs e)
        {
            base.OnPreLoad(e);
            if (!Page.IsPostBack)
            {
                if (AcmsContext != null && AcmsContext.CurrentPost != null)
                {
                    var siteDescription = System.Web.Configuration.WebConfigurationManager.AppSettings["SiteDescription"];
                    var tempTitle = new StringBuilder();
                    tempTitle.Append(AcmsContext.CurrentPost.DisplayName);
                    if (!string.IsNullOrEmpty(AcmsContext.CurrentPost.TitleSummary))
                    {
                        tempTitle.AppendFormat(" - {0}", AcmsContext.CurrentPost.TitleSummary);
                    }
                    
                    tempTitle.AppendFormat(" - {0}", AcmsContext.CurrentPost.SiteName);


                    if (!string.IsNullOrEmpty(siteDescription))
                    {
                        tempTitle.AppendFormat(" - {0}", siteDescription);
                    }
                    

                    Page.Header.Title = tempTitle.ToString();
                    
                    var description = new System.Web.UI.HtmlControls.HtmlMeta();
                    description.Name = "description";
                    description.Content = AcmsContext.CurrentPost.Summary;
                    Page.Header.Controls.Add(description);

                    if(!string.IsNullOrEmpty(AcmsContext.CurrentPost.MetaKeywords))
                    {
                        var keywords = new System.Web.UI.HtmlControls.HtmlMeta();
                        keywords.Name = "keywords";
                        keywords.Content = AcmsContext.CurrentPost.MetaKeywords;
                        Page.Header.Controls.Add(keywords);
                    }

                    //currentUrl = CurrentPost.Url;
                    //crrentPostDisplayName = CurrentPost.DisplayName;
                    //currentPostName = CurrentPost.Name;
                }
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            if (AcmsContext != null && AcmsContext.CurrentPost != null)
            {
                RegisterPost(AcmsContext.CurrentPost);
            }
            base.OnLoad(e);
        }

        protected override void OnLoadComplete(EventArgs e)
        {
            if (AcmsContext != null && !string.IsNullOrEmpty(AcmsContext.PostUrl))
            {
                //rewrite path back to original url so postbacks work seamlessly
                /*if (!string.IsNullOrEmpty(AcmsContext.OriginalUrl))
                {
                    Context.RewritePath(AcmsContext.OriginalUrl);
                }
                else
                {*/
                    StringBuilder newUrl = new StringBuilder();
                    newUrl.Append(AcmsContext.PostUrl);
                    if (!newUrl.ToString().Contains("?"))
                    {
                        newUrl.Append("?");
                    }
                    else if (Request.QueryString.ToString().Length > 0)
                    {
                        newUrl.Append("&");
                    }
                    if (Request.QueryString.ToString().Length > 0)
                    {
                        newUrl.Append(Request.QueryString.ToString());
                    }
                    Context.RewritePath(newUrl.ToString());
                //}
            }
            base.OnLoadComplete(e);
        }

        /*protected override System.Web.UI.PageStatePersister PageStatePersister
        {
            get
            {
                return this.AcmsPageStatePersister;
            }
        }*/

        private Acms.StateManager.WebPageStatePersister acmsPageStatePersister;
        /// <summary>
        /// Property PsgPageStatePersister
        /// </summary>
        public Acms.StateManager.WebPageStatePersister AcmsPageStatePersister
        {
            get
            {
                if (acmsPageStatePersister == null)
                {
                    acmsPageStatePersister = new Acms.StateManager.WebPageStatePersister(this);
                }
                return acmsPageStatePersister;
            }
        }

        /*protected override System.Collections.Specialized.NameValueCollection DeterminePostBackMode()
        {
            return AcmsPageStatePersister.DeterminePostBackMode();
        }*/

        //public new string Title { get; set; }

        protected override object SaveViewState()
        {
            ViewState["Title"] = this.Title;
            //ViewState["CurrentUrl"] = this.currentUrl;
            //ViewState["CurrentPostDisplayName"] = currentPostDisplayName;
            //ViewState["CurrentPostName"] = currentPostName;
            return base.SaveViewState();
        }

        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);
            this.Title = ViewState["Title"] as string;
            //this.currentUrl = ViewState["CurrentUrl"] as string;
            //currentPostDisplayName = ViewState["CurrentPostDisplayName"] as string;
            //currentPostName = ViewState["CurrentPostName"] as string;
        }

        public AcmsContext AcmsContext
        {
            get
            {
                return this.Context.Items["AcmsContext"] as AcmsContext;
            }
            set
            {
                this.Context.Items["AcmsContext"] = value;
            }
        }

        public new Acms.Bll.UserPrinciple User
        {
            get
            {
                return base.User as Acms.Bll.UserPrinciple;
            }

        }

        public string GetLoginUrl()
        {
            return string.Concat(System.Web.Security.FormsAuthentication.LoginUrl, System.Web.Security.FormsAuthentication.LoginUrl.Contains("?") ? "&" : "?", "ReturnUrl=", AcmsContext.PostUrl);
        }

        /*public string GetSiteRoot()
        {
            System.Text.StringBuilder siteRoot = new System.Text.StringBuilder();
            if(Request.IsSecureConnection)
                siteRoot.Append("https://");
            else
                siteRoot.Append("http://");
    
            siteRoot.Append(Request.ServerVariables["Server_Name"]);
            
            if (Request.Url.Port != 80)
            {
                siteRoot.Append(":");
                siteRoot.Append(Request.Url.Port);
            }
            siteRoot.Append(Request.ApplicationPath);

            if (!siteRoot.ToString().EndsWith("/"))
                siteRoot.Append("/");

            string tmp = siteRoot.ToString();
            return tmp.Substring(0, tmp.Length - 1);

        }*/

        private Dictionary<Post, List<PostControl>> registerdPost = new Dictionary<Post, List<PostControl>>();
        internal void RegisterPost(Post post)
        {
            if (post == null)
                return;
            if (!registerdPost.ContainsKey(post))
            {
                AdminControlRequiredDataBinding = true;
                registerdPost.Add(post, new List<PostControl>());
            }
            if (post.Controls != null)
            {
                foreach (PostControl ctrl in post.Controls)
                {
                    RegisterPostControl(post, ctrl);
                }
            }
        }

        internal void RegisterPostControl(Post post, PostControl postControl)
        {
            if (post == null || postControl == null)
                return;
            if (!registerdPost.ContainsKey(post))
            {
                RegisterPost(post);
            }

            if (registerdPost.ContainsKey(post))
            {
                if (!registerdPost[post].Contains(postControl))
                {
                    AdminControlRequiredDataBinding = true;
                    registerdPost[post].Add(postControl);
                }
            }
        }

        protected Acms.Bll.UserIdentity AcmsUser
        {
            get
            {
                if (User != null && User.Identity != null && User.Identity.IsAuthenticated)
                {
                    return User.Identity as Acms.Bll.UserIdentity;
                }
                else
                {
                    return null;
                }
            }
        }

        internal bool AdminControlRequiredDataBinding { get; private set; }

        internal Dictionary<Post, List<PostControl>> GetRegisteredPosts()
        {
            return registerdPost;
        }
    }
}
